﻿// -----------------------------------------------------------------------
// <copyright file="CustomToolPart.cs" company="">
// TODO: Update copyright text.
// </copyright>
// -----------------------------------------------------------------------

using System.Web;
using System.Web.UI.WebControls;
using LifeInSharePoint.Common;
using Microsoft.SharePoint;

namespace Metro.GridView.GridView
{
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.SharePoint.WebPartPages;

    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    public class CustomToolPart : ToolPart
    {
        protected Image image_;
        protected Label litBR;
        protected Label lblListsDD;
        protected DropDownList ListsDD;

        protected Label lblContentTypesDD;
        protected DropDownList ContentTypesDD;

        protected Label lblFieldCBL;
        protected CheckBoxList FieldCBL;

        protected Label litEndBR;
        protected GridView webPart;

        protected string LocalConfiguredList { get; set; }
        protected string LocalConfiguredContentTypes { get; set; }
        protected string LocalConfiguredFields { get; set; }

        protected override void OnInit(EventArgs e)
        {
            webPart = (GridView)this.ParentToolPane.SelectedWebPart;


            if (!Page.IsPostBack)
            {
                LocalConfiguredList = webPart.ConfiguredList;
                LocalConfiguredContentTypes = webPart.ConfiguredContentTypes;
                LocalConfiguredFields = webPart.ConfiguredFields;
            }


            base.OnInit(e);
        }

        protected override void CreateChildControls()
        {
            if (WebPartToEdit == null)
                return;

            litBR = new Label();
            litBR.Text = "<br>";
            Controls.Add(litBR);

            lblListsDD = new Label();
            lblListsDD.Text = "SharePoint Lists: ";
            Controls.Add(lblListsDD);

            ListsDD = new DropDownList();
            ListsDD.SelectedIndexChanged += new EventHandler(ListsDD_SelectedIndexChanged);
            ListsDD.AutoPostBack = true;
            this.Controls.Add(ListsDD);


            litBR = new Label();
            litBR.Text = "<br>";
            Controls.Add(litBR);

            lblContentTypesDD = new Label();
            lblContentTypesDD.Text = "SharePoint Content Types: ";
            Controls.Add(lblContentTypesDD);

            ContentTypesDD = new DropDownList();
            ContentTypesDD.SelectedIndexChanged += new EventHandler(ContentTypesDD_SelectedIndexChanged);
            ContentTypesDD.AutoPostBack = true;
            this.Controls.Add(ContentTypesDD);

            litBR = new Label();
            litBR.Text = "<br>";
            Controls.Add(litBR);

            lblFieldCBL = new Label();
            lblFieldCBL.Text = "Fields: ";
            Controls.Add(lblFieldCBL);

            FieldCBL = new CheckBoxList();
            Controls.Add(FieldCBL);

            litEndBR = new Label();
            litEndBR.Text = "<br><br><br><br>";
            Controls.Add(litEndBR);


            PopulateListsDropDown();
            if (!string.IsNullOrEmpty(LocalConfiguredList))
            {
                PopulateContentTypesDropDown();
            }

            //If there is a Content Type Configured then populate FieldsCBL
            if (!string.IsNullOrEmpty(LocalConfiguredList) && !string.IsNullOrEmpty(LocalConfiguredContentTypes))
            {
                PopulateFieldsCheckBoxList();
            }
            base.CreateChildControls();
        }

        void ContentTypesDD_SelectedIndexChanged(object sender, EventArgs e)
        {
            LocalConfiguredFields = string.Empty;
            ResetFieldsCheckBoxList();
            PopulateFieldsCheckBoxList();
        }

        void ListsDD_SelectedIndexChanged(object sender, EventArgs e)
        {
            LocalConfiguredList = string.Empty;
            LocalConfiguredContentTypes = string.Empty;
            LocalConfiguredFields = string.Empty;
            ResetContentTypeDropDown();
            ResetFieldsCheckBoxList();

            PopulateContentTypesDropDown();
        }

        private void ResetFieldsCheckBoxList()
        {
            FieldCBL.Items.Clear();
        }



        public override void ApplyChanges()
        {
            GridView webPart = (GridView)this.ParentToolPane.SelectedWebPart;
            if (webPart != null)
            {
                webPart.ConfiguredList = ListsDD.SelectedItem.Value;
                webPart.ConfiguredContentTypes = ContentTypesDD.SelectedItem.Value;
                webPart.ConfiguredFields = CBLToCSV(FieldCBL);

            }
        }

        private string CBLToCSV(CheckBoxList cbl)
        {
            // Get Values from CheckBoxList
            String values = "";
            for (int i = 0; i < cbl.Items.Count; i++)
            {
                if (cbl.Items[i].Selected)
                {
                    values += cbl.Items[i].Value + ";";
                }
            }

            values = values.TrimEnd(';');

            return values;
        }

        #region Populate DropDowns etc


        private void ResetListsDropDown()
        {
            ListsDD.Items.Clear();
            ListsDD.Items.Add(new ListItem("Select List", ""));
        }

        private void ResetContentTypeDropDown()
        {
            ContentTypesDD.Items.Clear();
            ContentTypesDD.Items.Add(new ListItem("Select Content Type", ""));
        }

        private void PopulateListsDropDown()
        {
            string ListSelectedValue = !string.IsNullOrEmpty(LocalConfiguredList) ? LocalConfiguredList : ListsDD.SelectedValue;

            SPWeb web = SPContext.Current.Web;
            SPListCollection webLists = web.Lists;
            ResetListsDropDown();
            foreach (SPList list in webLists)
            {
                ListItem item = new ListItem(list.Title, list.ID.ToString());
                if (!string.IsNullOrEmpty(ListSelectedValue) && list.ID.ToString() == ListSelectedValue)
                {
                    item.Selected = true;
                }

                ListsDD.Items.Add(item);
            }

        }

        private void PopulateContentTypesDropDown()
        {
            string ListSelectedValue = !string.IsNullOrEmpty(LocalConfiguredList) ? LocalConfiguredList : ListsDD.SelectedValue;
            string ContentTypeSelectedValue = !string.IsNullOrEmpty(LocalConfiguredContentTypes) ? LocalConfiguredContentTypes : ContentTypesDD.SelectedValue;

            SPList list = SPContext.Current.Web.Lists.GetList(new Guid(ListSelectedValue), true);
            SPContentTypeCollection listContentTypes = list.ContentTypes;

            //Clear the Field List when you change root list
            //FieldCBL.Items.Clear();
            ResetContentTypeDropDown();

            //Iterate through each Content Type found and display
            foreach (SPContentType type in listContentTypes)
            {
                ListItem item = new ListItem(type.Name, type.Id.ToString());
                if (!string.IsNullOrEmpty(ContentTypeSelectedValue) && type.Id.ToString() == ContentTypeSelectedValue)
                {
                    item.Selected = true;
                }

                ContentTypesDD.Items.Add(item);
            }
        }

        private void PopulateFieldsCheckBoxList()
        {
            string ListSelectedValue = !string.IsNullOrEmpty(LocalConfiguredList) ? LocalConfiguredList : ListsDD.SelectedValue;
            string ContentTypeSelectedValue = !string.IsNullOrEmpty(LocalConfiguredContentTypes) ? LocalConfiguredContentTypes : ContentTypesDD.SelectedValue;
            if (!string.IsNullOrEmpty(ContentTypeSelectedValue))
            {

                SPContentTypeId ctID = new SPContentTypeId(ContentTypeSelectedValue);
                SPContentType type = SPContext.Current.Web.Lists.GetList(new Guid(ListSelectedValue), true).ContentTypes[ctID];
                if (type != null)
                {
                    SPFieldCollection fieldCollection = type.Fields;
                    FieldCBL.Items.Clear();
                    foreach (SPField field in fieldCollection)
                    {
                        ListItem item = new ListItem(field.Title, field.InternalName + "," + field.Id);
                        //If the Configured Fields are set then check to see if current item is in that list and check it
                        if (!string.IsNullOrEmpty(CBLToCSV(FieldCBL)))
                        {
                            string[] Fields = CBLToCSV(FieldCBL).Split(new char[] { ';' });
                            if (Array.Exists(Fields, s => s.Contains(field.Title)))
                            {
                                item.Selected = true;
                            }
                        }
                        else
                        {
                            if (!field.Hidden)
                            {
                                item.Selected = true;
                            }
                        }
                        FieldCBL.Items.Add(item);
                    }
                }
            }
        }

        #endregion
    }
}